import classNames from 'classnames';
import React, { ReactNode, ReactElement, ReactChild } from 'react';

import { IDOMProps } from '../../utils/props';

import { Icon } from '../icon';
import { BarExtra } from './BarExtra';

interface IBarProps extends IDOMProps {
  className?: string;
  style?: React.CSSProperties;
  children?: React.ReactNode;
  showGoBackButton?: boolean;
  goBackButtonText?: string;
  onGoBack?: () => void;
}

interface IExtraButtonProps {
  iconType?: string;
  children?: React.ReactNode;
  onClick?: () => void;
  className?: string;
  style?: React.CSSProperties;
}
function ExtraButton({ iconType, children, onClick, style, className }: IExtraButtonProps) {
  return (
    <div className={classNames('br-bar__extra-tool', className)} onClick={onClick} style={style}>
      {iconType && <Icon className="br-bar__extra-tool--icon" type={iconType} />}
      {children}
    </div>
  );
}

export class Bar extends React.Component<IBarProps, {}> {
  public static Extra = BarExtra;
  public static ExtraButton = ExtraButton;
  public render() {
    const { className, style, onGoBack, goBackButtonText, showGoBackButton, ...domProps } = this.props;
    return (
      <div
        {...domProps as IDOMProps}
        className={classNames('br-bar', className)}
        style={style}
      >
        {
          showGoBackButton && <ExtraButton
            style={{ float: 'right' }}
            iconType="back"
            onClick={onGoBack}
          >
            {goBackButtonText || '返回'}
          </ExtraButton>
        }
        {
          React.Children.map(this.props.children, (child, index) => {
            if (typeof child === 'string' || typeof child === 'number') {
              return child;
            }
            if (child.type === BarExtra) {
              const children = React.Children.toArray(child.props.children);
              return React.cloneElement(child, undefined, ...children);
            }
            return child;
          })
        }
      </div>
    );
  }
}
